package com.zhentao.filter;

import com.zhentao.util.AppJwtUtil;
import io.jsonwebtoken.Claims;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono< Void > filter( ServerWebExchange exchange, GatewayFilterChain chain ) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if (path.contains( "login" ) || path.contains( "register" )|| path.contains( "getVerificationCode" )) {
            return chain.filter( exchange );
        }

        String token = request.getHeaders().getFirst( "Authorization" );

        if (token == null) {
            response.setStatusCode( HttpStatus.UNAUTHORIZED );
            return response.setComplete();
        }
        try {
            //解析token
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);

            //判断token
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == 1 || i == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //token如果是正确的,咱们执行操作的时候需要用到userId
            Object userId = claimsBody.get("id");
            //其他的业务里面要用到这个用户id  现在在过滤器里面
            // 把userId放到header里面
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId.toString());
            }).build();

            //重置header
            exchange.mutate().request(serverHttpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
